<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="物料代码" prop="materialCode">
        <el-input v-model="queryParams.materialCode" placeholder="请输入物料代码" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="收货编号" prop="receiptNumber">
        <el-input v-model="queryParams.receiptNumber" placeholder="请输入收货编号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="物料名称" prop="materialName">
        <el-input v-model="queryParams.materialName" placeholder="请输入物料名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="收货状态" prop="receiptStatus">
        <el-select v-model="queryParams.receiptStatus" placeholder="请选择收货状态" clearable>
          <el-option v-for="dict in dict.type.material_receiving_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="收货人姓名" prop="receiver">
        <el-input v-model="queryParams.receiver" placeholder="请输入收货人姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['material:MaterialRecord:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['material:MaterialRecord:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['material:MaterialRecord:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['material:MaterialRecord:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="MaterialRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="物料代码" align="center" prop="materialCode" />
      <el-table-column label="收货日期" align="center" prop="receiptDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.receiptDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货编号" align="center" prop="receiptNumber" />
      <el-table-column label="物料名称" align="center" prop="materialName" />
      <el-table-column label="供应商名称" align="center" prop="supplier" />
      <el-table-column label="生产厂家" align="center" prop="manufacturer" />
      <el-table-column label="厂家批号" align="center" prop="manufacturerBatchNumber" />
      <el-table-column label="生产日期" align="center" prop="productionDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.productionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保质期" align="center" prop="expirationDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expirationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="储存条件" align="center" prop="storageCondition" />
      <el-table-column label="物料规格" align="center" prop="specification" />
      <el-table-column label="收货总数量" align="center" prop="receivedQuantity" />
      <el-table-column label="拒收数量" align="center" prop="rejectedQuantity" />
      <el-table-column label="合格数量" align="center" prop="qualifiedQuantity" />
      <el-table-column label="收货状态" align="center" prop="receiptStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.material_receiving_status" :value="scope.row.receiptStatus" />
        </template>
      </el-table-column>
      <el-table-column label="收货人姓名" align="center" prop="receiver" />
      <el-table-column label="备注信息" align="center" prop="remarks" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['material:MaterialRecord:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['material:MaterialRecord:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改物料记录管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="供应商名称" prop="supplier">
          <el-input v-model="form.supplier" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="生产厂家" prop="manufacturer">
          <el-input v-model="form.manufacturer" placeholder="请输入生产厂家" />
        </el-form-item>
        <el-form-item label="厂家批号" prop="manufacturerBatchNumber">
          <el-input v-model="form.manufacturerBatchNumber" placeholder="请输入厂家批号" />
        </el-form-item>
        <el-form-item label="生产日期" prop="productionDate">
          <el-date-picker clearable v-model="form.productionDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择生产日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="保质期" prop="expirationDate">
          <el-date-picker clearable v-model="form.expirationDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择保质期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="储存条件" prop="storageCondition">
          <el-input v-model="form.storageCondition" placeholder="请输入储存条件" />
        </el-form-item>
        <el-form-item label="物料规格" prop="specification">
          <el-input v-model="form.specification" placeholder="请输入物料规格" />
        </el-form-item>
        <el-form-item label="收货总数量" prop="receivedQuantity">
          <el-input v-model="form.receivedQuantity" placeholder="请输入收货总数量" />
        </el-form-item>
        <el-form-item label="拒收数量" prop="rejectedQuantity">
          <el-input v-model="form.rejectedQuantity" placeholder="请输入拒收数量" />
        </el-form-item>
        <el-form-item label="收货人姓名" prop="receiver">
          <el-input v-model="form.receiver" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="备注信息" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增收货检查弹窗 -->
    <ReceiptCheckDialog :visible.sync="checkDialogVisible" @checkPass="handleCheckPass" />

  </div>
</template>

<script>
import { listMaterialRecord, getMaterialRecord, delMaterialRecord, addMaterialRecord, updateMaterialRecord } from "@/api/material/MaterialRecord"

import ReceiptCheckDialog from './ReceiptCheckDialog.vue'; // 引入新增的弹窗组件


export default {
  name: "MaterialRecord",
  dicts: ['material_receiving_status'],
  components: {
    ReceiptCheckDialog
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料记录管理表格数据
      MaterialRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialCode: null,
        receiptNumber: null,
        materialName: null,
        receiptStatus: null,
        receiver: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },

      // 新增控制收货检查弹窗显隐的变量
      checkDialogVisible: false,
      // 用于存储检查结果，可根据需要传递给后端或做其他处理
      checkResultData: null,

      isAdd: false, // 标记是否是“新增”操作


    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询物料记录管理列表 */
    getList() {
      this.loading = true
      listMaterialRecord(this.queryParams).then(response => {
        this.MaterialRecordList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        materialCode: null,
        receiptDate: null,
        receiptNumber: null,
        materialName: null,
        supplier: null,
        manufacturer: null,
        manufacturerBatchNumber: null,
        productionDate: null,
        expirationDate: null,
        storageCondition: null,
        specification: null,
        receivedQuantity: null,
        rejectedQuantity: null,
        qualifiedQuantity: null,
        receiptStatus: null,
        receiver: null,
        remarks: null,
        id: null,
        isDelete: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加物料记录管理"
      this.isAdd = true; // 标记为“新增”
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getMaterialRecord(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改物料记录管理"
        this.isAdd = false; // 标记为“修改”
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.isAdd) {
            // 【新增操作】才打开收货检查弹窗
            this.checkDialogVisible = true;
          } else {
            // 【修改操作】直接提交
            this.doSubmit();
          }
        }
      })
    },

    // 真正的提交逻辑（抽离出来复用）
    doSubmit() {
      if (this.form.id != null) {
        updateMaterialRecord(this.form).then(response => {
          this.$modal.msgSuccess("修改成功")
          this.open = false
          this.getList()
        })
      } else {
        addMaterialRecord(this.form).then(response => {
          this.$modal.msgSuccess("新增成功")
          this.open = false
          this.checkDialogVisible = false; // 新增成功后，关闭检查弹窗
          this.getList()
        })
      }
    },

    // 接收检查通过的回调（仅新增时会触发）
    handleCheckPass(data) {
      this.doSubmit(); // 执行提交
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除物料记录管理编号为"' + ids + '"的数据项？').then(function () {
        return delMaterialRecord(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('material/MaterialRecord/export', {
        ...this.queryParams
      }, `MaterialRecord_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>